#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define TRUE 0
#define FALSE 1

typedef struct LNode
{
    char name[20];
    int height;
    int weight;
    struct LNode *next;
}LNode,*Linklist;

Linklist Insert(Linklist head)
{
    int n,flag=FALSE;
    Linklist p,q=head;
    char temp;
    FILE *fp;
    fp=fopen("D:\\Develop\\C-Main\\DS_LiGuohe\\Chapter1\\Student.txt","r");
    if(head!=NULL)
    {
        while((q->next)!=NULL)  q=(Linklist)q->next;
        flag=TRUE;
    }
    while(1)
    {
        p=(Linklist)malloc(sizeof(LNode));
        p->next=NULL;
        fgets((p->name),20,fp);
        p->name[strlen(p->name)-1]='\0';
        fscanf(fp,"%d %d",&(p->weight),&(p->height));
        if(flag==TRUE)    q->next=(struct LNode*)p;
        else              head=p;
        q=p;
        flag=FALSE;
        temp=fgetc(fp);
        if(temp==EOF)  break;
    }
    fclose(fp);
    return(head);
}

void Write(Linklist head)
{
    FILE *fp;
    fp=fopen("D:\\Develop\\C-Main\\DS_LiGuohe\\Chapter1\\Student-Output.txt","w");
    Linklist p;
    p=head;
    fprintf(fp,"%-10s %-4s %-4s\n","姓名","体重","身高");
    while(p!=NULL)
    {
        fprintf(fp,"%-8s %-4d %-4d\n",p->name,p->weight,p->height);
        p=(Linklist)p->next;
    }
    fclose(fp);
}

Linklist Delete(Linklist head)
{
    int i;
    printf("请输入需要删除的位置：");
    scanf("%d",&i);
    Linklist p,q;
    if(i==1)
    {
        p=(Linklist)head->next;
        head=p;
        return (head);
    }
    p=head;
    int count=1;
    while(p&&count<i-1)
    {
        p=(Linklist)p->next;
        ++count;
    }
    if(!p||count>i)
    {
        printf("第%d个学生健康情况删除失败\n",i);
        return (head);
    }
    q=(Linklist)p->next;
    p->next=q->next;
    free(q);
    printf("第%d个学生健康情况删除成功\n",i);
    return(head);
}

void Getelem(Linklist head)
{
    int n;
    printf("请输入需要查询的位置:");
    scanf("%d",&n);
    Linklist p;
    p=head;
    int count=1,temp;
    while(p&&count<n)
    {
        p=p->next;
        count++;
    }
    if(!p||count>n) 
    {
        printf("输入的查询位置有误\n");
        return;
    }
    printf("第%d个学生健康情况输出:\n",n);
    printf("姓名\t\t体重\t身高\n");
    printf("%s\t\t%d\t%d\n",p->name,p->weight,p->height);
}

void Display(Linklist head)
{
    Linklist q;
    q=head;
    printf("学生健康情况输出:\n");
    printf("姓名\t\t体重\t身高\n");
    while(q!=NULL)
    {
        printf("%s\t\t%d\t%d\n",q->name,q->weight,q->height);
        q=(Linklist)q->next;
    }
}

int main()
{
    Linklist head;
    head=NULL;
    head=Insert(head);
    head=Delete(head);
    Getelem(head);
    Display(head);
    Write(head);
}